package com.adapter;

import java.util.List;

import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.adapter.AsyncImageLoader.ImageCallback;
import com.entity.YoukuVideo;
import com.videoplayer.R;

public class YoukuVideoListAdapter extends ArrayAdapter<YoukuVideo> {

	private ListView listView;
	private AsyncImageLoader asyncImageLoader;

	public YoukuVideoListAdapter(Activity activity,
			List<YoukuVideo> YoukuVideos, ListView listView) {
		super(activity, 0, YoukuVideos);
		this.listView = listView;
		asyncImageLoader = new AsyncImageLoader();
	}
	

	public View getView(int position, View convertView, ViewGroup parent) {
		Activity activity = (Activity) getContext();

		// Inflate the views from XML
		View rowView = convertView;
		ViewCache viewCache;
		if (rowView == null) {
			LayoutInflater inflater = activity.getLayoutInflater();
			rowView = inflater.inflate(R.layout.list_item, null);
			viewCache = new ViewCache(rowView);
			rowView.setTag(viewCache);
		} else {
			viewCache = (ViewCache) rowView.getTag();
		}
		YoukuVideo youku = getItem(position);

		if (youku != null) {
			// Load the image and set it on the ImageView
				String imageUrl = youku.getvImg();
				ImageView imageView = viewCache.getImageView();
				imageView.setTag(imageUrl);

				Drawable cachedImage = asyncImageLoader.loadDrawable(imageUrl,
						new ImageCallback() {
							public void imageLoaded(Drawable imageDrawable,
									String imageUrl) {
								ImageView imageViewByTag = (ImageView) listView
										.findViewWithTag(imageUrl);
								if (imageViewByTag != null) {
									imageViewByTag
									.setBackgroundDrawable(imageDrawable);
								}
							}
						});

				if (cachedImage == null) {
//					imageView.setImageResource(R.drawable.detail_pic_loading);
					imageView.setBackgroundResource(R.drawable.detail_pic_loading);
				} else {
//					imageView.setImageDrawable(cachedImage);
					imageView.setBackgroundDrawable(cachedImage);
				}
			// Set the text on the TextView
			TextView textView = viewCache.getTextView();
			textView.setText(youku.getvTitle());
		}
		

		return rowView;
	}

}
